package com.info.zhiduoduo.weixin.service;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.mapper.Condition;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.google.common.collect.Lists;
import com.info.zhiduoduo.common.configs.CommonConfig;
import com.info.zhiduoduo.common.configs.MailConfig;
import com.info.zhiduoduo.common.constants.Constants;
import com.info.zhiduoduo.common.constants.SmartResult;
import com.info.zhiduoduo.common.constants.StatusMsg;
import com.info.zhiduoduo.common.constants.company.CompanyAccountFlowBizType;
import com.info.zhiduoduo.common.constants.system.UserType;
import com.info.zhiduoduo.common.exception.Asserts;
import com.info.zhiduoduo.common.exception.SmartException;
import com.info.zhiduoduo.common.formbean.BaseAuthInfo;
import com.info.zhiduoduo.common.formbean.BaseSimpleFormBean;
import com.info.zhiduoduo.common.utils.DateUtil;
import com.info.zhiduoduo.common.utils.MD5Util;
import com.info.zhiduoduo.common.utils.NumberUtil;
import com.info.zhiduoduo.common.utils.RandomUtil;
import com.info.zhiduoduo.common.utils.StringUtil;
import com.info.zhiduoduo.core.configs.Redis.RedisKey;
import com.info.zhiduoduo.core.service.CommonService;
import com.info.zhiduoduo.core.service.CoreCompanyService;
import com.info.zhiduoduo.core.service.MailService;
import com.info.zhiduoduo.core.service.WxMessageService;
import com.info.zhiduoduo.core.service.common.BaseService;
import com.info.zhiduoduo.core.service.common.ContractDocService;
import com.info.zhiduoduo.core.service.common.DocService;
import com.info.zhiduoduo.core.service.common.RedisService;
import com.info.zhiduoduo.core.service.impl.CeoNoticeService;
import com.info.zhiduoduo.repository.dto.company.*;
import com.info.zhiduoduo.repository.dto.maker.MakerIntroDto;
import com.info.zhiduoduo.repository.dto.project.UserProjectDto;
import com.info.zhiduoduo.repository.entity.company.*;
import com.info.zhiduoduo.repository.entity.crowdsource.CrowdsourceCompanyParty;
import com.info.zhiduoduo.repository.entity.maker.Maker;
import com.info.zhiduoduo.repository.entity.maker.MakerBankcard;
import com.info.zhiduoduo.repository.entity.maker.MakerStudio;
import com.info.zhiduoduo.repository.entity.partner.PartnerAccount;
import com.info.zhiduoduo.repository.entity.pay.PaymentMerchant;
import com.info.zhiduoduo.repository.entity.system.Bank;
import com.info.zhiduoduo.repository.mapper.company.*;
import com.info.zhiduoduo.repository.mapper.crowdsource.CrowdsourceProjectMapper;
import com.info.zhiduoduo.repository.mapper.entrustmentproject.EntrustmentProjectItemMapper;
import com.info.zhiduoduo.repository.mapper.maker.MakerMapper;
import com.info.zhiduoduo.repository.mapper.maker.MakerStudioMapper;
import com.info.zhiduoduo.repository.mapper.maker.MakerTagMapper;
import com.info.zhiduoduo.repository.mapper.weixin.WxNoticeMapper;
import com.info.zhiduoduo.weixin.formbean.company.*;
import com.info.zhiduoduo.weixin.formbean.maker.EmailFormBean;
import com.info.zhiduoduo.weixin.formbean.maker.ForgetPayPwdFormBean;
import com.info.zhiduoduo.weixin.formbean.maker.PayPwdFormBean;
import com.info.zhiduoduo.weixin.formbean.project.ProjectIdFormBean;
import com.info.zhiduoduo.wxsdk.WxApiService;
import com.info.zhiduoduo.wxsdk.domain.app.WxAuthorizeAccessToken;
import com.info.zhiduoduo.wxsdk.domain.app.WxAuthorizeUserInfo;

import com.taobao.api.internal.util.DESUtil;
import org.apache.commons.io.FilenameUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.io.File;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import javax.annotation.Resource;
import javax.validation.Valid;

@Transactional
@Service
public class CompanyService extends BaseService {

	@Resource
	MakerMapper makerMapper;

	@Resource
	CompanyMapper companyMapper;

	@Resource
	CompanyAccountMapper companyAccountMapper;

	@Resource
	CompanyPaymentMapper companyPaymentMapper;

	@Resource
	ComplianceIntelligenceMapper complianceIntelligenceMapper;

	@Resource
	EnterpriseRefundMapper enterpriseRefundMapper;

	@Resource
	CompanyProjectMapper companyProjectMapper;

	@Resource
	CompanyUserMapper companyUserMapper;

	@Resource
	MakerTagMapper makerTagMapper;

	@Autowired
	CommonConfig commonConfig;

	@Autowired
	WxApiService wxApiService;

	@Autowired
	MailConfig mailConfig;

	@Autowired
	WxMessageService wxMessageService;
	@Resource
	WxNoticeMapper wxNoticeMapper;

	@Autowired
	CeoNoticeService ceoNoticeService;

	@Autowired
	CommonService commonService;

	@Autowired
	DocService docService;

	@Autowired
	ContractDocService contractDocService;

	@Autowired
	MailService mailService;

	@Autowired
	RedisService redisService;

	@Resource
	CrowdsourceProjectMapper crowdsourceProjectMapper;
	@Resource
	EntrustmentProjectItemMapper entrustmentProjectItemMapper;
	@Resource
	MakerStudioMapper makerStudioMapper;
	@Resource
	CompanyPartyMapper companyPartyMapper;

	@Autowired
	CoreCompanyService coreCompanyService;

	@Resource
	CompanyZhaoshangSubLedgerMapper companyZhaoshangSubLedgerMapper;
	@Resource
	CompanyZhaoshangSubLedgerRechargeMapper companyZhaoshangSubLedgerRechargeMapper;

	public SmartResult regCompany(BaseSimpleFormBean<RegCompanyFormBean> baseSimpleFormBean) {

		SmartResult smartResult = new SmartResult();

		RegCompanyFormBean regCompanyFormBean = baseSimpleFormBean.getReqdata();

		if (null == regCompanyFormBean || StringUtil.isEmpty(regCompanyFormBean.getPhone()) ||
				StringUtil.isEmpty(regCompanyFormBean.getVerifycode()) || baseSimpleFormBean.getUserid() == 0) {
			smartResult.setStateMsg(StatusMsg.StatusMsg_101);
			return smartResult;
		}

		int compid = baseSimpleFormBean.getUserid();
		String phone = regCompanyFormBean.getPhone();

		Company company = new Company().selectById(compid);
		if (null == company) {
			smartResult.setStateMsg(StatusMsg.StatusMsg_302);
			return smartResult;
		} else if (company.getState() >= Constants.comp_state_1) {
			smartResult.setStateMsg(StatusMsg.StatusMsg_316);
			return smartResult;
		}

		//检查手机号是否已注册过企业
		Company company2 = companyMapper.checkCompanyExistByPhone(phone);
		if (company2 != null) {
			smartResult.setStateMsg(StatusMsg.StatusMsg_116);
			return smartResult;
		}

		//查看个人是否已经注册
		Maker maker = makerMapper.checkUserExistByPhone(phone);
		if (null != maker) {
			smartResult.setStateMsg(StatusMsg.StatusMsg_118);
			return smartResult;
		}

		commonService.checkPhoneVerifyCode(phone, regCompanyFormBean.getVerifycode());

		String password = regCompanyFormBean.getPassword();

		String salt = RandomUtil.generateString(8);
		company.setSalt(salt);
		company.setPassword(MD5Util.md5(password + salt));
		//验证合伙人的邀请码是否有效
		String inviteCode = regCompanyFormBean.getInviteCode();
		if (StringUtil.isNotEmpty(inviteCode)) {
			int count = new PartnerAccount().selectCount(Condition.create().eq("promo_code", inviteCode));
			if (count == 0) {
				return smartResult(StatusMsg.StatusMsg_505);
			}
		}
		//更新手机号
		company.setRegphone(phone).setInviteCode(inviteCode).setState(Constants.comp_state_1);

		if (company.updateById()) {
			//注册成功,开通企业账户
			new CompanyAccount().setCompid(compid).insert();
		}

		return smartResult();
	}

	public SmartResult getLoginInfo(BaseSimpleFormBean<LoginFormBean> baseSimpleFormBean) {
		SmartResult smartResult = new SmartResult();

		LoginFormBean loginFormBean = baseSimpleFormBean.getReqdata();

		if (null == loginFormBean || StringUtil.isEmpty(loginFormBean.getPhone()) || StringUtil.isEmpty(loginFormBean.getPassword())) {
			smartResult.setStateMsg(StatusMsg.StatusMsg_101);
			return smartResult;
		}

		Company company = companyMapper.checkCompanyExistByPhone(loginFormBean.getPhone());

		if (null == company) {
			smartResult.setStateMsg(StatusMsg.StatusMsg_302);
			return smartResult;
		}

		String pwdDescrypt = "";
		try {
			pwdDescrypt = DESUtil.decrypt(loginFormBean.getPassword(), Constants.PWD_DES_KEY);
		} catch (Exception e) {
			throw new SmartException(StatusMsg.StatusMsg_150);
		}
		String md5Pwd = MD5Util.md5(pwdDescrypt + company.getSalt());
		if (!md5Pwd.equals(company.getPassword())) {
			smartResult.setStateMsg(StatusMsg.StatusMsg_115);
			return smartResult;
		}

		return smartResult;
	}

	public SmartResult alterLoginInfo(BaseSimpleFormBean<AlterLoginInfoFormBean> formBean) {
		AlterLoginInfoFormBean reqdata = formBean.getReqdata();
		if (reqdata == null) return errorParamSmartResult();

		String openid = reqdata.getOpenid();
		//0:旧手机号 1：企业名称
		int type = reqdata.getType();
		String compname = reqdata.getCompname();
		String payPassword = reqdata.getPayPassword();
		String oldPhone = reqdata.getOldPhone();
		String oldPassword = reqdata.getOldPassword();
		String newPhone = reqdata.getNewPhone();
		String newPassword = reqdata.getNewPassword();
		String verifyCode = reqdata.getVerifycode();
		String avatar = reqdata.getAvatar();
		String nickName = reqdata.getNickname();

		if (StringUtil.isAnyEmpty(openid, newPhone, newPassword, verifyCode)) {
			return errorParamSmartResult();
		}

		//根据旧资料判断参数是否正常
		if ((type == 0 && StringUtil.isAnyEmpty(oldPhone, oldPassword)) || (type == 1 && StringUtil.isAnyEmpty(compname, payPassword))) {
			return errorParamSmartResult();
		}

		//新手机号是否被注册
		int compCount = new Company().selectCount(Condition.create().eq("regphone", newPhone));
		if (compCount > 0) return smartResult(StatusMsg.StatusMsg_116);
		int userCount = new Maker().selectCount(Condition.create().eq("phone", newPhone));
		if (userCount > 0) return smartResult(StatusMsg.StatusMsg_118);

		Company company;
		if (type == 0) {
			//通过登陆手机号修改
			company = new Company().selectOne(Condition.create().eq("regphone", oldPhone));
			if (company == null) return smartResult(StatusMsg.StatusMsg_302);

			String md5 = MD5Util.md5(oldPassword + company.getSalt());
			if (!company.getPassword().equals(md5)) return smartResult(StatusMsg.StatusMsg_115);

		} else {
			//通过企业名和支付密码修改
			company = new Company().selectOne(Condition.create().eq("compname", compname));
			if (company == null) return smartResult(StatusMsg.StatusMsg_302);
			CompanyAccount account = new CompanyAccount().selectOne(Condition.create().eq("compid", company.getCompid()));
			if (account == null) return smartResult(StatusMsg.StatusMsg_302);

			String md5 = MD5Util.md5(payPassword + account.getSalt());
			if (!account.getPayPassword().equals(md5)) return smartResult(StatusMsg.StatusMsg_113);
		}

		//新的openid是否已经被注册
		Company companyByOpenid = companyMapper.getCompanyByOpenid(openid);
		if (companyByOpenid != null) {
			if (!companyByOpenid.getCompid().equals(company.getCompid()) && companyByOpenid.getState() >= Constants.comp_state_1) {
				//新openid关联的企业已经是绑定了手机号，且与旧手机号绑定的企业不是同一个企业，则不能更换
				return smartResult(StatusMsg.StatusMsg_119);
			} else if (!companyByOpenid.getCompid().equals(company.getCompid())) {
				//只要不是同一家企业，且新openid关联的企业是未绑定手机的，就删除新openid关联的企业
				companyByOpenid.deleteById();
			} else {
				//新openid关联的企业与旧手机号绑定的企业是同一家企业，不处理，可以直接更换。
			}
		}
		Maker makerByOpenid = makerMapper.getUserByOpenid(openid);
		if (makerByOpenid != null) {
			if (makerByOpenid.getState() != Constants.user_state_1) {
				//已存在认证的创客，返回
				return smartResult(StatusMsg.StatusMsg_120);
			} else {
				makerByOpenid.deleteById();
			}
		}

		commonService.checkPhoneVerifyCode(newPhone, verifyCode);

		//更新openid\手机号和密码
		company.setOpenid(openid)
				.setRegphone(newPhone)
				.setPassword(MD5Util.md5(newPassword + company.getSalt()))
				.setAvatar(avatar)
				.setNickname(nickName)
				.updateById();

		return smartResult(company.getCompid());
	}

	public SmartResult authCompany(BaseSimpleFormBean<AuthCompanyFormBean> baseSimpleFormBean) {
		SmartResult smartResult = new SmartResult();

		AuthCompanyFormBean reqdata = baseSimpleFormBean.getReqdata();

		if (null == reqdata) {
			smartResult.setStateMsg(StatusMsg.StatusMsg_101);
			return smartResult;
		}

		int compid = baseSimpleFormBean.getUserid();
		Company company = new Company().selectById(compid);
		if (null == company) {
			smartResult.setStateMsg(StatusMsg.StatusMsg_302);
			return smartResult;
		}

		int count = new Company().selectCount(Condition.create()
				.eq("compname", reqdata.getCompname())
				.or()
				.eq("creditcode", reqdata.getCreditcode())
				.andNew()
				.ne("compid", company.getCompid()));
		if (count > 0) return smartResult(StatusMsg.StatusMsg_317);

		CompanyAccount companyAccount = new CompanyAccount().selectOne(Condition.create().eq("compid", compid));
		if (null == companyAccount) return smartResult(StatusMsg.StatusMsg_302);

		BeanUtils.copyProperties(reqdata, company);
		company.setState(Constants.comp_state_2).updateById();

		BeanUtils.copyProperties(reqdata, companyAccount);
		if (!CollectionUtils.isEmpty(reqdata.getShareholder())) {
			companyAccount.setShareholder(JSON.toJSONString(reqdata.getShareholder()));
		}
		if (companyAccount.getAuthSubmitTime() == null) {
			companyAccount.setAuthSubmitTime(new Date());
		}
		companyAccount.setRealnameAuth(Constants.comp_auth_1).updateById();

		ceoNoticeService.recordCompanyVerify(compid, 0);
		wxMessageService.notifyCompanyAgents(compid);
		return smartResult;
	}

	public SmartResult updateCompanyRealInfo(BaseSimpleFormBean<AuthCompanyFormBean> formBean) {
		SmartResult smartResult = new SmartResult();

		AuthCompanyFormBean reqdata = formBean.getReqdata();

		if (null == reqdata) {
			smartResult.setStateMsg(StatusMsg.StatusMsg_101);
			return smartResult;
		}

		int compid = formBean.getUserid();
		Company company = new Company().selectById(compid);
		if (null == company) {
			smartResult.setStateMsg(StatusMsg.StatusMsg_302);
			return smartResult;
		}

		int count = new Company().selectCount(Condition.create()
				.eq("compname", reqdata.getCompname())
				.or()
				.eq("creditcode", reqdata.getCreditcode())
				.andNew()
				.ne("compid", company.getCompid()));
		if (count > 0) return smartResult(StatusMsg.StatusMsg_317);

		CompanyAccount companyAccount = new CompanyAccount().selectOne(Condition.create().eq("compid", compid));
		if (null == companyAccount) return smartResult(StatusMsg.StatusMsg_302);

		BeanUtils.copyProperties(reqdata, company);
		company.updateById();

		BeanUtils.copyProperties(reqdata, companyAccount);
		if (!CollectionUtils.isEmpty(reqdata.getShareholder())) {
			companyAccount.setShareholder(JSON.toJSONString(reqdata.getShareholder()));
		}
		companyAccount.updateById();

		return smartResult;
	}

	public SmartResult<CompanyDetailDto> getCompanyInfo(BaseAuthInfo baseAuthInfo) {

		CompanyDetailDto company = getCompanyInfo(baseAuthInfo.getUserid());
		if (null == company) {
			return smartResult(StatusMsg.StatusMsg_302);
		}

		return smartResult(company);
	}

	public CompanyDetailDto getCompanyInfo(Integer compid) {
		if (compid == null) return null;

		CompanyDetailDto companyInfo = coreCompanyService.getCompanyInfo(compid);
		if (companyInfo == null) return null;

		//认证失败了,返回驳回原因
		if (companyInfo.getState() == Constants.comp_state_3) {
			CompanyAuthRecord record = new CompanyAuthRecord().selectOne(
					Condition.create().eq("compid", companyInfo.getCompid()).eq("state", 1).orderBy("id", false).last("limit 1"));
			if (record != null) {
				companyInfo.setRejectReason(record.getReason());
			}
		}

		return companyInfo;
	}

	/**
	 * 获取企业收藏的创客
	 */
	public SmartResult getCompUser(BaseSimpleFormBean<String> formBean) {
		Page<Object> page = PageHelper.startPage(formBean.getPage(), formBean.getRows());
		List<MakerIntroDto> userList = companyUserMapper.getCompUserList(formBean.getUserid(), formBean.getReqdata());
		userList.forEach(dto -> {
			int userid = dto.getUserid();
			int count = new MakerBankcard().selectCount(
					Condition.create().eq("userid", dto.getUserid()).eq("accttype", Constants.BANK_ACCT_TYPE_COMPANY).eq("state", 1));
			dto.setBankcardType(count > 0 ? 1 : 0);
			dto.setTagList(makerTagMapper.getUserTagList(userid));
		});

		return smartResultPage(page);
	}

	public SmartResult updateCompanyInfo(BaseSimpleFormBean<CompanyInfoFormBean> baseSimpleFormBean) {
		SmartResult smartResult = new SmartResult();
		CompanyInfoFormBean companyInfoFormBean = baseSimpleFormBean.getReqdata();
		if (null == companyInfoFormBean) {
			smartResult.setStateMsg(StatusMsg.StatusMsg_101);
			return smartResult;
		}
		Company company = new Company().selectById(baseSimpleFormBean.getUserid());
		if (null == company) {
			smartResult.setStateMsg(StatusMsg.StatusMsg_302);
			return smartResult;
		}
		BeanUtils.copyProperties(companyInfoFormBean, company);
		company.updateById();
		CompanyAccount companyAccount = new CompanyAccount().selectOne(Condition.create().eq("compid", company.getCompid()));
		if(null != companyAccount){
			if(StringUtil.isNotEmpty(companyInfoFormBean.getRealname()) && StringUtil.isNotEmpty(companyInfoFormBean.getIdno())){
				companyAccount.setRealname(companyInfoFormBean.getRealname());
				companyAccount.setIdno(companyInfoFormBean.getIdno());
				companyAccount.updateById();
			}
		}
		return smartResult;
	}

	public SmartResult updatePayPwd(BaseSimpleFormBean<PayPwdFormBean> baseSimpleFormBean) {
		SmartResult smartResult = new SmartResult();

		PayPwdFormBean payPwdFormBean = baseSimpleFormBean.getReqdata();

		if (null == payPwdFormBean || StringUtil.isEmpty(payPwdFormBean.getPayPassword()) ||
				baseSimpleFormBean.getIdtype() != UserType.COMPANY) {
			smartResult.setStateMsg(StatusMsg.StatusMsg_101);
			return smartResult;
		}

		String payPwd = payPwdFormBean.getPayPassword();
		int userid = baseSimpleFormBean.getUserid();

		CompanyAccount companyAccount = new CompanyAccount().selectOne(Condition.create().eq("compid", userid));

		if (null == companyAccount) {
			smartResult.setStateMsg(StatusMsg.StatusMsg_302);
			return smartResult;
		}

		String salt = RandomUtil.generateString(8);
		companyAccount.setSalt(salt);
		companyAccount.setPayPassword(MD5Util.md5(payPwd + salt));
		companyAccount.updateById();

		return smartResult;
	}

	public SmartResult getPayPwdForCheck(BaseSimpleFormBean<PayPwdFormBean> baseSimpleFormBean) {
		SmartResult smartResult = new SmartResult();

		PayPwdFormBean payPwdFormBean = baseSimpleFormBean.getReqdata();

		if (null == payPwdFormBean || StringUtil.isEmpty(payPwdFormBean.getPayPassword()) ||
				baseSimpleFormBean.getIdtype() != UserType.COMPANY) {
			smartResult.setStateMsg(StatusMsg.StatusMsg_101);
			return smartResult;
		}

		String payPwd = payPwdFormBean.getPayPassword();
		int userid = baseSimpleFormBean.getUserid();

		CompanyAccount companyAccount = new CompanyAccount().selectOne(Condition.create().eq("compid", userid));
		if (null == companyAccount) {
			smartResult.setStateMsg(StatusMsg.StatusMsg_302);
			return smartResult;
		}

		String salt = companyAccount.getSalt();
		String md5PayPwd = MD5Util.md5(payPwd + salt);

		if (!md5PayPwd.equals(companyAccount.getPayPassword())) {
			smartResult.setStateMsg(StatusMsg.StatusMsg_113);
			return smartResult;
		}

		return smartResult;

	}

	public SmartResult updatePayPwdForForget(BaseSimpleFormBean<ForgetPayPwdFormBean> baseSimpleFormBean) {
		SmartResult smartResult = new SmartResult();

		ForgetPayPwdFormBean forgetPayPwdFormBean = baseSimpleFormBean.getReqdata();

		if (null == forgetPayPwdFormBean || StringUtil.isEmpty(forgetPayPwdFormBean.getPayPassword()) ||
				baseSimpleFormBean.getIdtype() != UserType.COMPANY) {
			smartResult.setStateMsg(StatusMsg.StatusMsg_101);
			return smartResult;
		}

		int userid = baseSimpleFormBean.getUserid();
		String phone = forgetPayPwdFormBean.getPhone();
		String verifyCode = forgetPayPwdFormBean.getVerifycode();

		Company company = new Company().selectById(userid);
		if (!company.getRegphone().equals(phone)) {
			smartResult.setStateMsg(StatusMsg.StatusMsg_114);
			return smartResult;
		}

		commonService.checkPhoneVerifyCode(phone, verifyCode);

		CompanyAccount companyAccount = new CompanyAccount().selectOne(Condition.create().eq("compid", userid));

		if (null == companyAccount) {
			return smartResult(StatusMsg.StatusMsg_201);
		}

		String salt = RandomUtil.generateString(8);

		companyAccount.setSalt(salt);
		companyAccount.setPayPassword(MD5Util.md5(forgetPayPwdFormBean.getPayPassword() + salt));
		companyAccount.updateById();

		return smartResult();
	}

	/**
	 * 通过银行名，查询银行编号
	 */
	public SmartResult queryBankno(BaseSimpleFormBean<String> formBean) {
		String bankname = formBean.getReqdata();
		if (StringUtil.isEmpty(bankname)) return errorParamSmartResult();

		Page<Object> page = PageHelper.startPage(formBean.getPage(), formBean.getRows());
		new Bank().selectList(Condition.create().like("bankname", bankname));
		return smartResultPage(page);
	}

	/**
	 * 绑定企业账号
	 */
	public SmartResult bindCompany(BaseSimpleFormBean<BindCompanyFormBean> formBean) {

		BindCompanyFormBean reqdata = formBean.getReqdata();
		String code = reqdata.getCode();
		String phone = reqdata.getPhone();
		String password = reqdata.getPassword();

		WxAuthorizeAccessToken authorizeAccessToken = wxApiService.getAuthorizeAccessToken(code);
		if (authorizeAccessToken == null) {
			return smartResult(StatusMsg.StatusMsg_101);
		}

		String openid = authorizeAccessToken.getOpenid();
		String accessToken = authorizeAccessToken.getAccess_token();

		Company companyByOpenid = companyMapper.getCompanyByOpenid(openid);
		if (companyByOpenid != null) {
			if (NumberUtil.safeInt(companyByOpenid.getState()) > 1) {
				//openid已经注册并认证了手机号，不可绑定企业。
				return smartResult(StatusMsg.StatusMsg_119);
			} else {
				//删除这个openid还未认证的企业
				companyByOpenid.deleteById();
			}
		}

		Maker makerByOpenid = makerMapper.getUserByOpenid(openid);
		if (makerByOpenid != null) {
			if (NumberUtil.safeInt(makerByOpenid.getState()) > 1) {
				//openid已经注册创客并认证了手机号，不可绑定企业。
				return smartResult(StatusMsg.StatusMsg_120);
			} else {
				//删除这个openid还未认证的企业
				makerByOpenid.deleteById();
			}
		}

		Company company = new Company().selectOne(Condition.create().eq("regphone", phone));
		if (company == null) return smartResult(StatusMsg.StatusMsg_114);
		if (StringUtil.isNotEmpty(company.getOpenid())) return smartResult(StatusMsg.StatusMsg_314);

		if (!MD5Util.md5(password + company.getSalt()).equals(company.getPassword())) {
			return smartResult(StatusMsg.StatusMsg_115);
		}

		CompanyAccount companyAccount = new CompanyAccount().selectOne(Condition.create().eq("compid", company.getCompid()));
		if (null == companyAccount) return smartResult(StatusMsg.StatusMsg_302);
		if (!CollectionUtils.isEmpty(reqdata.getShareholder())) {
			companyAccount.setShareholder(JSON.toJSONString(reqdata.getShareholder())).updateById();
		}

		WxAuthorizeUserInfo userInfo = wxApiService.getAuthorizeUserInfo(accessToken, openid);
		company.setOpenid(openid)
				.setAvatar(userInfo.getHeadimgurl())
				.setNickname(userInfo.getNickname())
				.setUnionid(userInfo.getUnionid())
				.setSex((StringUtil.toInt(userInfo.getSex())))
				.setState(Constants.comp_state_2);
		company.updateById();

		return smartResult(company.getCompid());
	}

	public SmartResult getIntelCrowdsourceList(BaseSimpleFormBean<String> formBean) {
		String compname = formBean.getReqdata();
		Page<Object> page = PageHelper.startPage(formBean.getPage(), formBean.getRows());
		List<CompanyBriefDto> companyBriefDtos = companyMapper.getIntelCrowdsourceCompanyByName(compname);
//		companyBriefDtos.forEach(companyBrief -> {
//			if (2 == companyBrief.getCrowdsourceCity()){
//				companyBrief.setWhether(true);
//			} else {
//				companyBrief.setWhether(false);
//			}
//		});
		return smartResultPage(page);
	}

	// ******************************************* 开联通账户信息查询 *******************************//
//
//	public SmartResult getMerchantAccountInfoFromKlt(BaseSimpleFormBean<Integer> formBean) {
//		Integer compid = formBean.getReqdata();
//
//		return smartResult(coreCompanyService.getMerchantAccountInfo(compid));
//	}

	public SmartResult agreeProtocol(BaseSimpleFormBean formBean) {
		int userid = formBean.getUserid();
		int idtype = formBean.getIdtype();
		if (idtype != UserType.COMPANY) return errorParamSmartResult();

		boolean update = new CompanyAccount().setAgreeProtocol(1).update(Condition.create().eq("compid", userid));
		if (update) return smartResult();
		return optFailSmartResult();
	}

	public SmartResult editMail(BaseSimpleFormBean<EmailFormBean> formBean) {
		EmailFormBean reqdata = formBean.getReqdata();
		String email = reqdata.getEmail();
		int userid = formBean.getUserid();
		Company company = new Company().selectById(userid);
		if (company == null) return smartResult(StatusMsg.StatusMsg_201);

		boolean update = company.setCompemail(email).updateById();
		if (update) return smartResult();
		return optFailSmartResult();
	}

//	public SmartResult sendContractEmail(BaseSimpleFormBean<ProjectIdFormBean> formBean) {
//		ProjectIdFormBean reqdata = formBean.getReqdata();
//		int projectid = reqdata.getProjectid();
//
//		CompanyProject project = new CompanyProject().selectById(projectid);
//		if (project == null) {
//			return smartResult(StatusMsg.StatusMsg_301);
//		}
//
//		CompanyDetailDto company = companyMapper.getCompanyInfo(project.getCompid());
//		if (company == null) {
//			return smartResult(StatusMsg.StatusMsg_302);
//		}
//
//		MakerStudio studio = new MakerStudio().selectById(project.getUserid());
//		if (studio == null) {
//			return smartResult(StatusMsg.StatusMsg_201);
//		}
//
//		File file = docService.getOrCreateContractFile(project, company, studio, null);
//		if (file == null) return optFailSmartResult();
//
//		String subject = "项目合同-" + FilenameUtils.getBaseName(file.getName());
//		String date = DateUtil.getString(project.getProjectstart(), DateUtil.FORMAT_STYLE_3);
//		String content = String.format(mailConfig.getContractMailContent(), date, company.getCompname(), studio.getUsername());
//
//		ArrayList<String> toList = Lists.newArrayList(company.getCompemail());
//		ArrayList<String> attachments = Lists.newArrayList(file.getAbsolutePath());
//
//		boolean sent = mailService.sendMailWithAttachments(toList, subject, content, attachments);
//		if (sent) return smartResult();
//		return optFailSmartResult();
//	}

	public SmartResult sendPdfContractEmail(BaseSimpleFormBean<ProjectIdFormBean> formBean) {
		ProjectIdFormBean reqdata = formBean.getReqdata();
		int projectid = reqdata.getProjectid();

		CompanyProject project = new CompanyProject().selectById(projectid);
		if (project == null) {
			return smartResult(StatusMsg.StatusMsg_301);
		}

		Company company = companyMapper.selectById(project.getCompid());
		if (company == null) {
			return smartResult(StatusMsg.StatusMsg_302);
		}

		MakerStudio studio = new MakerStudio().selectById(project.getUserid());
		if (studio == null) {
			return smartResult(StatusMsg.StatusMsg_201);
		}

		File file = contractDocService.createContractFile(project.getProjectid());
		if (file == null) return optFailSmartResult();

		String subject = "项目合同-" + FilenameUtils.getBaseName(file.getName());
		String date = DateUtil.getString(project.getProjectstart(), DateUtil.FORMAT_STYLE_3);
		String content = String.format(mailConfig.getContractMailContent(), date, company.getCompname(), studio.getUsername());

		ArrayList<String> toList = Lists.newArrayList(company.getCompemail());
		ArrayList<String> attachments = Lists.newArrayList(file.getAbsolutePath());

		boolean sent = mailService.sendMailWithAttachments(toList, subject, content, attachments);
		if (sent) return smartResult();
		return optFailSmartResult();
	}

	public SmartResult saveTodayAmountReminder(BaseSimpleFormBean<Integer> formBean) {
		int userid = formBean.getUserid();
		@Valid Integer state = formBean.getReqdata();
		if (state == null) state = 0;
		else if (state > 0) state = 1;

		new CompanyAccount().setTodayAmountReminder(state).update(Condition.create().eq("compid", userid));
		return smartResult();
	}

	public SmartResult queryCompanyProjectList(BaseSimpleFormBean<QueryCompanyProjectListFormBean> formBean) {
		SmartResult smartResult = new SmartResult();
		QueryCompanyProjectListFormBean reqdata = formBean.getReqdata();
		/**
		 * 判断是否存在该企业
		 */
		Integer companyFlag = companyMapper.checkCompanyExistById(reqdata.getCompanyId());
		if (companyFlag == 0) {
			return smartResult(StatusMsg.StatusMsg_302);
		}
		Page page = PageHelper.startPage(formBean.getPage(), formBean.getRows());
		List<UserProjectDto> result = companyProjectMapper.getListByCompanyIdAndUserId(reqdata.getCompanyId(), reqdata.getUserId());
		smartResult.setList(result);

		smartResult.setTotalpages(page.getPages());
		smartResult.setCurrpage(formBean.getPage());
		smartResult.setTotalrecords(page.getTotal());
		return smartResult;
	}

	//创建充值申请
	public SmartResult applyRecharge(BaseSimpleFormBean<ApplyRechargeFormBean> formBean){
		ApplyRechargeFormBean reqdata = formBean.getReqdata();
		//检查企业是否存在
		Company company = new Company().selectById(reqdata.getCompid());
		if (company == null) return smartResult(StatusMsg.StatusMsg_302);

		CompanyRecharge recharge = new CompanyRecharge();
		recharge.setAmount(reqdata.getAmount());
		recharge.setCompid(reqdata.getCompid());
		recharge.setReceiptimg(reqdata.getReceiptimg());
		recharge.setPayId(reqdata.getPayId());
		String rechargeno = RandomUtil.createRandomNo("REC", "");
		recharge.setRechargeno(rechargeno);
		//新增
		recharge.insert();

		//微信通知财务
		wxMessageService.notifyCompanyApplyRecharge(company.getCompname());

		return smartResult();
	}

	//删除充值申请
	public SmartResult delApplyRecharge(BaseSimpleFormBean<DelRechargeFormBean> formBean){
		CompanyRecharge recharge = new CompanyRecharge().selectById(formBean.getReqdata().getRechargeid());
		if (recharge.getState() == 2) return smartResult(StatusMsg.StatusMsg_309);

		recharge.deleteById();
		return smartResult();
	}

	public SmartResult<CompanyZhaoShangSubLedgerDto> listZhaoShangSubLedger(BaseSimpleFormBean<ListZhaoShangSubLedgerFormBean> formBean) {
		int userid = formBean.getUserid();
		ListZhaoShangSubLedgerFormBean reqdata = formBean.getReqdata();
		String compname = reqdata.getCompname();
		int merchantId = reqdata.getMerchantId();
		Date from = DateUtil.defaultInitial(reqdata.getFrom());
		Date to = DateUtil.defaultNow(reqdata.getTo());

		Page<CompanyZhaoShangSubLedgerDto> page = PageHelper.startPage(formBean.getPage(), formBean.getRows());
		companyZhaoshangSubLedgerMapper.listByMerchantIdAndCompname(userid, compname, merchantId, from, to);
//		.forEach(dto -> {
//			int payMerchant = ZddMerchantType.convert(PayAccount.convert(dto.getPayType()));
//			dto.setCurrentPayMerchant(payMerchant == dto.getMerchantId());
//		});
		return SmartResult.ofPage(page);
	}

	public SmartResult<CompanyZhaoshangSubLedgerRechargeDto> listZhaoShangSubLedgerRecharge(
			BaseSimpleFormBean<ListZhaoShangSubLedgerRechargeFormBean> formBean) {
		int userid = formBean.getUserid();
		ListZhaoShangSubLedgerRechargeFormBean reqdata = formBean.getReqdata();
		String compname = reqdata.getCompname();
		int merchantId = reqdata.getMerchantId();
		String orderNo = reqdata.getOrderNo();
		Date from = DateUtil.defaultInitial(reqdata.getFrom());
		Date to = DateUtil.defaultNow(reqdata.getTo());

		Page<CompanyZhaoshangSubLedgerRechargeDto> page = PageHelper.startPage(formBean.getPage(), formBean.getRows());
		companyZhaoshangSubLedgerRechargeMapper.listByMerchantIdAndName(userid, compname, merchantId, orderNo, from, to);

		return SmartResult.ofPage(page);
	}
	//智合规展示
	public SmartResult intelligentComplianceDisplay(BaseSimpleFormBean<Integer> formBean) {
		Integer compid = formBean.getReqdata();
		if (compid == null || compid <= 0) return errorParamSmartResult();
		//判断企业是否存在
		Company company = new Company().selectById(compid);
		Asserts.notNull(company, StatusMsg.StatusMsg_302);
		//获取展示页面
		IntelligentComplianceDisplayDto list = complianceIntelligenceMapper.intelligentComplianceDisplay(compid);
		//获取排名占比
		list.setRankingProportion(complianceIntelligenceMapper.getRankingProportion(list.getCompid()));

		return smartResult(list);
	}

	public SmartResult getEnterpriseCustomerService(BaseSimpleFormBean<Integer> formBean) {
		Integer compid = formBean.getReqdata();
		if (compid == null || compid <= 0) return errorParamSmartResult();
		//判断企业是否存在
		Company company = new Company().selectById(compid);
		Asserts.notNull(company, StatusMsg.StatusMsg_302);

		EnterpriseCustomerServiceFormBean dto = new EnterpriseCustomerServiceFormBean();
		dto.setCustomerServicePhone(company.getCustomerServicePhone())
				.setCustomerServiceNickname(company.getCustomerServiceNickname());
		return smartResult(dto);
	}
	public SmartResult<EnterpriseAgreementDto> getEnterpriseAgreement(BaseSimpleFormBean<Integer> formBean) {
		if(formBean.getReqdata() == null){
			return errorParamSmartResult();
		}
		CompanyAgreement companyAgreement = new CompanyAgreement()
				.selectOne(Condition.create().eq("compid", formBean.getReqdata()));
		Asserts.notNull(companyAgreement , StatusMsg.StatusMsg_102);

		EnterpriseAgreementDto dto = new EnterpriseAgreementDto();
		BeanUtils.copyProperties(companyAgreement, dto);
		Company company = new Company().selectById(companyAgreement.getCompid());
		Asserts.notNull(company , StatusMsg.StatusMsg_102);
		dto.setCompName(company.getCompname());
		return SmartResult.success(dto);
	}

	//企业申请退款
	public SmartResult businessesApplyRorARefund(BaseSimpleFormBean<EnterpriseRefundFormBean> formBean){
		EnterpriseRefundFormBean reqdata = formBean.getReqdata();
		//确认企业是否存在
		Company company = new Company().selectById(formBean.getUserid());
		if (company == null) return smartResult(StatusMsg.StatusMsg_302);
		//查询企业支付方式余额
		CompanyPayment companyPayment = companyPaymentMapper.getCompanyPayment(company.getCompid(),reqdata.getPayId());
		if (companyPayment == null) return smartResult(StatusMsg.StatusMsg_330);

		BigDecimal beforeBalance = companyPayment.getBalance();
		BigDecimal currBalance = companyPayment.getBalance().subtract(reqdata.getAmountOfMoney());

		//添加申请记录
		EnterpriseRefund enterpriseRefund = new EnterpriseRefund();
		enterpriseRefund.setCompId(formBean.getUserid())
						.setPayId(reqdata.getPayId())
						.setType(reqdata.getType())
						.setAmountOfMoney(reqdata.getAmountOfMoney());
		if (enterpriseRefund.insert()){
			//确认完成,生成企业流水
			CompanyAccountflow companyAccountflow = new CompanyAccountflow();
			companyAccountflow.setCompid(enterpriseRefund.getCompId())
							  .setFlowAmount(reqdata.getAmountOfMoney())
							  .setPayId(reqdata.getPayId())
							  .setBeforeBalance(beforeBalance)
							  .setCurrBalance(currBalance)
							  .setBizid(enterpriseRefund.getId())
							  .setBizType(CompanyAccountFlowBizType.BUSINESSES_APPLY_FOR_A_REFUND)
							  .setFlowtype(2)
							  .setFlowname("企业申请退款");
			if (!companyAccountflow.insert()){
				return smartResult(StatusMsg.StatusMsg_375);
			}
			//企业余额扣款
			companyPayment.setBalance(currBalance).updateById();
			//通知符嘉琳userid3246 企业申请退款
			wxMessageService.enterpriseApplicationDorRefund("oB8CR0Sn146ZlrB8XvKN_bekmcLM",3,company.getCompname(),reqdata.getAmountOfMoney(),0);

			return smartResult();
		}
		return smartResult(StatusMsg.StatusMsg_199);
	}

	//企业申请退款列表
	public SmartResult<EnterpriseRefund> businessesApplyRorARefundList(BaseSimpleFormBean<Integer> formBean) {
		Page<EnterpriseRefund> page = PageHelper.startPage(formBean.getPage(), formBean.getRows());
		enterpriseRefundMapper.getCompanyRefund(formBean.getUserid(),formBean.getReqdata());
		return SmartResult.ofPage(page);
	}
	public SmartResult<String> getCompanyName(BaseSimpleFormBean<Integer> formBean) {
		Company company = companyMapper.selectById(formBean.getReqdata());
		if (null == company){
			return emptyDataSmartResult();
		}
		return SmartResult.success(company.getCompname());
	}

	public SmartResult getPartyInfo(BaseSimpleFormBean<Integer> formBean) {
		CrowdsourceCompanyParty party = new CrowdsourceCompanyParty().selectById(formBean.getReqdata());
		return SmartResult.success(party);
	}
	//获取企业各业务支付配置
	public SmartResult getCompanyPartyList(BaseSimpleFormBean formBean) {
		Integer compid = formBean.getUserid();
		Company company = new Company().selectById(compid);
		CompanyAccount companyAccount = companyAccountMapper.getByCompid(compid);
		List<CompanyPayBalanceDto> list = coreCompanyService.getCompanyAllBalanceList(compid);
		Map<String, List<CompanyPayBalanceDto>> collect = list.stream().collect(Collectors.groupingBy(CompanyPayBalanceDto::getBusinessSn));
		// 未开通业务的移除
		if (!company.getOpenZdd()) {
			collect.remove(Constants.BUSINESS_SN_ZDD);
		}
		if (company.getIntelCrowdsource() == 1) {
			collect.remove(Constants.BUSINESS_SN_CRO);
		}
		if (company.getOpenOddJob() == 0) {
			collect.remove(Constants.BUSINESS_SN_ODD);
		}
		if (companyAccount.getMakerGroupon() == 0) {
			collect.remove(Constants.BUSINESS_SN_GROUP);
		}
		CompanyPartyListFormBean result = new CompanyPartyListFormBean();
		result.setMap(collect);
		result.setInvoiceScope(company.getInvoiceScope());
		result.setInvoiceScopeOdd(company.getInvoiceScopeOdd());
		result.setTotalBalance(coreCompanyService.getCompanyTotalBalance(compid));
		return SmartResult.success(result);
	}

	/**
	 * 首页报表数据
	 * @param formBean
	 * @return
	 */
	public SmartResult homePageReport(BaseSimpleFormBean formBean) {
		int compid = formBean.getUserid();
		HomeDataReportBean bean = new HomeDataReportBean();

		// 查询企业是否正在生成项目验收单，生成过程中待验收项目数量返回0
		String key = RedisKey.genCompGeneralProjectDeliveryKey(compid);
		if (redisService.hasKey(key)) {
			bean.setDeliveryProState(1);
			bean.setZddDeliverNum(0);
			bean.setLongDeliverNum(0);
			bean.setCroDeliverNum(0);
			bean.setOddDeliverNum(0);
			bean.setGrouponDeliverNum(0);
		} else {
			List<String> zddProIds = companyProjectMapper.getCompProjectDeliveryNum(compid, 1);
			List<String> longProIds = companyProjectMapper.getCompProjectDeliveryNum(compid, 4);
			List<String> croProIds = crowdsourceProjectMapper.getCompProjectDeliveryNum(compid, 1);
			List<String> oddProIds = crowdsourceProjectMapper.getCompProjectDeliveryNum(compid, 2);
			bean.setZddDeliverNum(zddProIds.size());
			bean.setLongDeliverNum(longProIds.size());
			bean.setCroDeliverNum(croProIds.size());
			bean.setOddDeliverNum(oddProIds.size());
			bean.setGrouponDeliverNum(entrustmentProjectItemMapper.getCompProjectDeliveryNum(compid,0).size());
		}

		// 创客注册进展数量
		bean.setPendingTaxAcctNum(makerStudioMapper.getCompUnOpenTaxAcctNum(compid));

		// 返回企业待验收项目数量（ 项目）
		bean.setCheckingZddProNum(companyProjectMapper.getProCheckingNum(compid));

		// 项目数+智众包项目数+智零工项目数
		bean.setAllProNum(companyProjectMapper.getAllProNum(compid));

		// 未读消息数量
		bean.setUnreadMsgNum(wxNoticeMapper.queryCompWxNoticeUnRead(compid));
		return smartResult(bean);
	}

	public SmartResult getPayMerchantList(BaseSimpleFormBean<QueryPayMerchantFormBean> formBean) {
		Integer paymentComp = formBean.getReqdata().getPaymentComp();
		List<PaymentMerchant> list = new PaymentMerchant()
				.selectList(Condition.create()
									 .eq(paymentComp != null && paymentComp != 0 ,"payment_comp",paymentComp));
		return SmartResult.success(list);
	}

	public List<CompanyPayment> getCompanyPayList(Integer compid) {
		return companyPaymentMapper.getCompanyPayList(compid);
	}

	//修改企业业务支付配置为默认
	public SmartResult setCompanyPartyDefault(BaseSimpleFormBean<UpdateCompanyPartyFormBean> formBean){
		Integer compid = formBean.getUserid();
		UpdateCompanyPartyFormBean req = formBean.getReqdata();
		List<CompanyParty> list = companyPartyMapper.getCompanyPartyList(compid,req.getBusinessSn());
		for (CompanyParty p:list) {
			//相等设置为默认
			Integer isDefault = p.getId().equals(req.getId()) ? 1 : 0;
			p.setIsDefault(isDefault).updateById();
		}
		return SmartResult.success();
	}
}
